package com.appsky.drift.async_task;

import java.io.IOException;
import java.net.SocketTimeoutException;

import com.appsky.drift.api.AppSkyApp;
import com.appsky.drift.api.DLog;
import com.appsky.drift.api.JsonFactory;
import com.appsky.drift.api.ServiceConnection;
import com.appsky.drift.api.Utils;

import android.content.Context;
import android.os.AsyncTask;

public class LoginTask extends AsyncTask<String, Object, Integer> {

	private Context context = null;
	private ServiceConnection connection = null;

	public LoginTask(Context context) {
		this.context = context;
	}

	@Override
	protected Integer doInBackground(String... params) {
		return login();
	}

	private int login() {
		int resultFlag;
		String respond;
		JsonFactory jsonFactory = JsonFactory.getFactory();
		AppSkyApp app = (AppSkyApp) context.getApplicationContext();
		
		String loginJson = jsonFactory.makeUserLoginJson(
				app.myInfo.getUserId(), app.myInfo.getLatitude(),
				app.myInfo.getLongitude(), app.myInfo.getNick(),
				app.myInfo.getSex()).toJSONString();

		try {
			connection = ServiceConnection.getConnection(app.getIp());
			respond = loginAndResult(loginJson);// 从服务器返回周围人列表
			DLog.i("login receive: " + respond);
			
			resultFlag = app.myInfo.parseLoginJson(respond);
			connection.setTimeout(0);
		} catch (SocketTimeoutException e) {
			resultFlag = Utils.LOGIN_TIMEOUT;
		} catch (IOException e) {
			resultFlag = Utils.LOGIN_ERROR;
		}
		return resultFlag;
	}
		
	private String loginAndResult(String loginMessage)
			throws SocketTimeoutException, IOException {
		connection.setTimeout(30 * 1000);
		connection.sendMessage(loginMessage);
		return connection.readMessage();
	}
}
